import paramiko
import time
import pyautogui
import os

# SSH 连接配置
hostname = '192.168.2.65'  # 远程服务器地址
port = 22                      # SSH 端口
username = 'ute'     # 用户名
password = 'ute'     # 密码

# 创建 SSH 客户端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 启用 X11 转发
ssh.load_system_host_keys()
ssh.connect(hostname, port, username, password, look_for_keys=False, allow_agent=False)

stdin, stdout, stderr = ssh.exec_command('echo $DISPLAY')
print(stderr.read())
print(stdout.read())
remote_display = stdout.read().decode().strip()
print(f"Remote DISPLAY: {remote_display}")

# 获取 X11 转发的 DISPLAY 值
transport = ssh.get_transport()
if transport is not None:
    # transport.set_x11_forward(True)  # 启用 X11 转发
    display = transport.get_x11_display()
    if display:
        print(f"X11 DISPLAY: {display}")
    else:
        print("X11 forwarding is not enabled.")
else:
    print("Failed to establish SSH transport.")

# 设置远程服务器的 DISPLAY 环境变量
if display:
    # 获取本地机器的 X11 授权信息
    xauth_cmd = 'xauth list'  # 获取本地机器的 X11 授权信息
    stdin, stdout, stderr = ssh.exec_command(xauth_cmd)
    xauth_output = stdout.read().decode().strip()

    # 解析 X11 授权信息（获取 MIT-MAGIC-COOKIE）
    xauth_lines = xauth_output.split('\n')
    if xauth_lines:
        # 取第一行的授权信息
        xauth_entry = xauth_lines[0]
        print(f"X11 Auth Entry: {xauth_entry}")

        # 提取 MIT-MAGIC-COOKIE
        xauth_parts = xauth_entry.split()
        if len(xauth_parts) >= 3:
            cookie = xauth_parts[2]
            print(f"MIT-MAGIC-COOKIE: {cookie}")

            # 在远程服务器上添加 X11 授权
            add_xauth_cmd = f'xauth add {display} . {cookie}'
            stdin, stdout, stderr = ssh.exec_command(add_xauth_cmd)
            print("X11 authorization added on remote server.")

    # 设置 DISPLAY 环境变量
    set_display_cmd = f'export DISPLAY={display}; echo $DISPLAY'
    stdin, stdout, stderr = ssh.exec_command(set_display_cmd)
    print("Remote DISPLAY:", stdout.read().decode().strip())

    # 切换到 /home/ute/kaishi 目录
    cd_cmd = 'cd /home/ute/kaishi'
    stdin, stdout, stderr = ssh.exec_command(cd_cmd)
    print("Changed directory to /home/ute/kaishi")

    # 以非阻塞方式启动 Java 程序
    java_cmd = 'java SimpleGUI &'  # 替换为你的 Java 程序
    stdin, stdout, stderr = ssh.exec_command(java_cmd)
    print("Java program started in non-blocking mode.")
    # 等待 Java 程序启动
    time.sleep(5)  # 根据实际情况调整等待时间

    # 使用 pyautogui 操控鼠标
    try:
        # 设置本地 DISPLAY 环境变量
        os.environ['DISPLAY'] = display

        # 获取屏幕分辨率
        screen_width, screen_height = pyautogui.size()
        print(f"Screen resolution: {screen_width}x{screen_height}")

        # 移动鼠标到 (100, 100) 并点击
        pyautogui.moveTo(100, 100)
        pyautogui.click()
        print("Mouse moved and clicked at (100, 100).")
    except Exception as e:
        print(f"Error controlling mouse: {e}")
else:
    print("Cannot proceed without X11 forwarding.")

# 关闭 SSH 连接
ssh.close()